package com.link.base.base.coupons.service;

import com.link.base.base.coupons.model.CollectRecord;
import com.link.base.base.coupons.model.Coupons;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.Filter;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.cllog.LCLogger;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>优惠券-定时更新优惠卷</p>
 * @author 汪大伟
 * @date 2018/6/8
 */

@Component
public class CoupScheduledTasks {

    @Resource
    private CouponsService couponsService;

    @Resource
    private CollectRecordService collectRecordService;

    /**
     * 定时过期优惠卷
     * @author : 汪大伟
     * @throws Exception 异常
     * @date : 2018/6/8
     */
    @Transactional(rollbackFor = BasicServiceException.class)
    public void couponsTasks() throws Exception {
        // 查询优惠券信息，每次批最多更新2000条数据，防止OOM。
        Boolean stopLoop = true;
        Integer page = 2000;
        Integer rows = 1;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss ");
        String date = sdf.format(new Date());
        //记录更新数量
        int updateNum = 0;
        Coupons coupons = new Coupons();
        coupons.setIsEffect("Y");
        String CashCoupon = "CashCoupon";
        coupons.setCouponsType(CashCoupon);
        List<Coupons> coupList = new ArrayList<>();
        while (stopLoop) {
            coupons.setRows(rows);
            coupons.setPage(page);
            // 查询当前优惠券，每次最多查询2000条数据（当前记录数小于当前页数，表示最后一页）
            coupList = couponsService.queryByExamplePage(coupons);
            // 如果当前页是最后一页结束循环
            if (coupList.size() < page) {
                stopLoop = false;
            }
            for (Coupons entity : coupList) {
                if (entity.getEffectEndTime() != null && entity.getEffectStaTime() != null) {
                    Boolean flag = entity.getEffectEndTime().compareTo(date) < 0
                            || entity.getEffectStaTime().compareTo(date) > 0;
                    // 更新过期优惠券状态
                    if ( flag && !"N".equals(entity.getIsEffect())) {
                        entity.setIsEffect("N");
                        entity.setRow_status("UPDATE");
                        couponsService.upsert(entity);
                        updateNum++;
                    }
                    {
                        continue;
                    }
                }
            }
            // 清除list数据，释放内存防止OOM
            coupList.clear();
            // 翻页拿到下一页数据
            rows ++;
        }
        LCLogger.info().withMessage("更新数据：=============" + updateNum + "条" + "=========");
    }

    /**
     * 定时更新领取明细表里面的领取状态
     * @author : 汪大伟
     * @throws Exception 异常
     * @date : 2018/6/8
     */
    @Transactional(rollbackFor = BasicServiceException.class)
    public void collectRecordTasks() throws Exception {
        //记录更新数量
        int updateNum = 0;
        String used = "Used";
        Boolean stopLoop = true;
        // 查询优惠券领取记录信息，每次批最多更新2000条数据，防止OOM。
        Integer page = 2000;
        Integer rows = 1;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss ");
        String date = sdf.format(new Date());
        QueryParams queryParams = new QueryParams();
        CollectRecord collectRecord = new CollectRecord();
        String expired = "Expired";
        queryParams.addFilter(new Filter("claimStatus","claimStatus","<>",expired));
        List<CollectRecord> collectRecordList = new ArrayList<>();
        while (stopLoop) {
            queryParams.setRows(rows);
            queryParams.setPage(page);
            // 查询当前优惠券领取记录信息，每次最多查询2000条数据
            collectRecord = (CollectRecord) BasicModel.transformClass(CollectRecord.class, queryParams);
            collectRecordList = collectRecordService.queryByExamplePage(collectRecord);
            // 如果当前页是最后一页结束循环（当前记录数小于当前页数，表示最后一页）
            if (collectRecordList.size() < page) {
                stopLoop = false;
            }
            for (CollectRecord entity : collectRecordList) {
                if (entity.getEffectEndTime() != null) {
                    if (entity.getEffectEndTime().compareTo(date) < 0
                            && !expired.equals(entity.getClaimStatus())
                            && !used.equals(entity.getClaimStatus())) {
                        entity.setClaimStatus(expired);
                        entity.setRow_status("UPDATE");
                        collectRecordService.upsert(entity);
                        updateNum++;
                    }
                    {
                        continue;
                    }
                }
            }
            // 清除list数据，释放内存防止OOM
            collectRecordList.clear();
            // 翻页拿到下一页数据
            rows ++;
        }
        LCLogger.info().withMessage("更新数据：=============" + updateNum + "条" + "=========");
    }
}
